package butines.game.pathfinder;
import java.util.HashMap;


public class Graph {

	private HashMap<Integer, Node> nodes = new HashMap<Integer, Node>();
	
	public Graph() {
		
	}

	public boolean isEmpty() {
		return nodes.isEmpty();
	}
	
	public Node createNode(int x, int y) {
		Node node = new Node(x, y);
		nodes.put(node.getId(), node);
		return node;
	}

	public void removeNode(Node node) {
		if (node == null) {
			throw new IllegalArgumentException("Argument 'node' is null");
		}
		
		Edges edges = node.getEdges();
		edges.destory();
		
		nodes.remove(node.getId());
	}
	
	public Node getNode(int id) {
		return nodes.get(id);
	}
	
	public void createEdge(int idFrom, int idTo, float cost) {
		Node from = getNode(idFrom);
		Node to  = getNode(idTo);
		if (from == null) {
			throw new IllegalArgumentException("Argument 'from' is null");
		}
		if (to == null) {
			throw new IllegalArgumentException("Argumetn 'to' is null");
		}
		Edges edges = from.getEdges();
		if (edges.exists(to) == false) {
			Edge edge = new Edge(from, to, cost);
			edges.add(edge);
		}
	}
	
	public void removeEdge(int idFrom, int idTo) {
		Node from = getNode(idFrom);
		Node to  = getNode(idTo);
		if (from == null) {
			throw new IllegalArgumentException("Argument 'from' is null");
		}
		if (to == null) {
			throw new IllegalArgumentException("Argumetn 'to' is null");
		}
		Edges edges = from.getEdges();
		edges.remove(to);
	}
	
	public Edge getEdge(int idFrom, int idTo) {
		Node from = getNode(idFrom);
		Node to = getNode(idTo);
		return (from == null || to == null) ? null : from.getEdges().get(to);
	}
	
	public boolean existsNode(int idFrom) {
		return nodes.containsKey(idFrom);
	}
	
	public boolean existsEdge(int idFrom, int idTo) {
		Node from = getNode(idFrom);
		Node to  = getNode(idTo);
		return (from == null || to == null) ? false : from.getEdges().exists(to);
	}
	
	public int countNodes() {
		return nodes.size();
	}

	public int countEdges() {
		int count = 0;
		for (Node node: nodes.values()) {
			count += node.getEdges().count();
		}
		return count;
	}

	public void removeEdges() {
		for (Node node: nodes.values()) {
			node.getEdges().removeAll();
		}
	}
	
	public void removeNodes() {
		removeEdges();
		nodes.clear();
	}
	
}
